package com.javabi.codegenerator.java.object.datastore.method.sql;

import static com.javabi.codeobject.java.name.JavaName.toLower;

import com.javabi.codegenerator.java.model.bean.JavaModelBean;
import com.javabi.codegenerator.java.model.bean.JavaModelBeanField;
import com.javabi.codegenerator.java.model.datastore.JavaModelDataStore;
import com.javabi.codegenerator.java.object.datastore.method.GetAllMethod;
import com.javabi.codeobject.java.type.IJavaType;
import com.javabi.codetype.sql.builder.ISqlBuilder;
import com.javabi.codetype.sql.executor.ISqlValues;
import com.javabi.codetype.sql.executor.SqlValues;

public class SqlGetAllMethod extends GetAllMethod {

	public SqlGetAllMethod(JavaModelDataStore dataStore) {
		super(dataStore);
		setOverride();

		JavaModelBean bean = dataStore.getElementBean();
		IJavaType parserType = bean.getResultSetParser().getType();

		getReferences().add(ISqlBuilder.class);
		getReferences().add(ISqlValues.class);
		getReferences().add(SqlValues.class);
		getReferences().add(parserType);

		setSqlContents(bean, parserType);
	}

	private void setSqlContents(JavaModelBean bean, IJavaType parserType) {
		SqlCodeLines code = new SqlCodeLines();
		code.emptyLine();
		code.line("// SQL");
		code.line("ISqlBuilder sql = newSqlBuilder();");
		code.line("sql.select();");

		// Columns
		boolean comma = false;
		for (JavaModelBeanField field : bean.getFieldList()) {
			if (comma) {
				code.line("sql.sql(',');");
			}
			comma = true;
			code.line("sql.column(\"" + toLower(field.getName()) + "\");");
		}
		code.line("sql.from(getTable());");

		// Execute
		code.emptyLine();
		code.line("// Execute");
		code.line("return getExecutor().getList(sql, new " + parserType + "());");
		setContents(code);
	}
}
